package com.hcb.tonguetiphealth.manager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.util.HttpUtils;

public class AsyncBitmapLoader {  
	public  int iconType = 0;
	public static final int headIcon = 1;
	public static final int wineIcon = 2;
	public static final int mealIcon = 3;
	public static final int cateIcon = 4;
	public static final int restaurantIcon = 5;
	private  String iconPath = "";
	private static final String headPath = "head/";
	private static final String winePath = "wine/";
	private static final String mealPath = "meal/";
	private static final String catePath = "cate/";
	private static final String restaurantPath = "restaurant/";
	
//	@SuppressLint("SdCardPath")
	private static final String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/TongueTipHealth/";
	private static AsyncBitmapLoader asyncBitmapLoader = null;
	private Options opt;
    /** 
     * 内存图片软引用缓冲 
     */  
    private HashMap<String, SoftReference<Bitmap>> imageCache = null;  
      
    private AsyncBitmapLoader() {  
        opt = new BitmapFactory.Options();
    	opt.inSampleSize = 1; //使用缩略图，缩小倍数
        imageCache = new HashMap<String, SoftReference<Bitmap>>();  
    }  
    public static AsyncBitmapLoader getInstance() {
    	if(asyncBitmapLoader == null) {
    		asyncBitmapLoader = new AsyncBitmapLoader();
    	}
		return asyncBitmapLoader;
    }
    public Bitmap loadBitmap(final ImageView imageView, final String imageURL, final ImageCallBack imageCallBack) {  
    	//在内存缓存中，则返回Bitmap对象  
        if(imageCache.containsKey(getFileName(imageURL))) {  
            SoftReference<Bitmap> reference = imageCache.get(getFileName(imageURL));  
            Bitmap bitmap = reference.get();  
            if(bitmap != null) {  
            	if(Global.DEBUG) {
            		System.out.println("------- 图片在内存缓存中");
            	}
                return bitmap;  
            }  
        } else {  
            /** 
             * 加上一个对本地缓存的查找 
             */  
            String bitmapName = getFileName(imageURL);  
            File cacheDir = new File(getLocalPath());  
            File[] cacheFiles = cacheDir.listFiles();  
            int i = 0;  
            if(null != cacheFiles) {
	            for(; i<cacheFiles.length; i++) {  
	                if(cacheFiles[i].length()>0 && bitmapName.equals(cacheFiles[i].getName())) {  
	                    break;  
	                }  
	            }  
	            if(i < cacheFiles.length) {  
	            	if(Global.DEBUG) {
	            		System.out.println("------- 图片在本地缓存中");
	            	}
	            	Bitmap bitmap = BitmapFactory.decodeFile(getLocalPath() + bitmapName, opt); 
	            	imageCache.put(getFileName(imageURL), new SoftReference<Bitmap>(bitmap)); 
	                return bitmap;  
	            }
            }
        }  
          
        final Handler handler = new Handler() {  
            /* (non-Javadoc) 
             * @see android.os.Handler#handleMessage(android.os.Message) 
             */  
            @Override  
            public void handleMessage(Message msg) {  
                // TODO Auto-generated method stub  
                imageCallBack.imageLoad(imageView, (Bitmap)msg.obj);  
                if(Global.DEBUG) {
            		System.out.println("------- 图片从网络中下载");
            	}
            }  
        };  
          
        //如果不在内存缓存中，也不在本地（被jvm回收掉），则开启线程下载图片  
        new Thread() {  
            /* (non-Javadoc) 
             * @see java.lang.Thread#run() 
             */  
            @Override  
            public void run()  {  
                // TODO Auto-generated method stub  
                InputStream bitmapIs = HttpUtils.retriveInputSteam(imageURL);  
                Bitmap bitmap = BitmapFactory.decodeStream(bitmapIs, null, opt);  
                try {
					bitmapIs.close();
				} catch (IOException e) {
					e.printStackTrace();
				} catch(Exception e) {
					e.printStackTrace();
				}
                imageCache.put(getFileName(imageURL), new SoftReference<Bitmap>(bitmap));  
                
                
                
                File dir = new File(getLocalPath());  
                if(!dir.exists()) {  
                    dir.mkdir();  
                }  
                  
                File bitmapFile = new File(getLocalPath() + getFileName(imageURL));  
                if(!bitmapFile.exists()) {  
                    try {  
                        bitmapFile.createNewFile();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                }  
                File parent = bitmapFile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                
                FileOutputStream fos = null;  
                try {  
                    fos = new FileOutputStream(bitmapFile, false);  
                    if( !bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)  || bitmapFile.length()==0) {
                    	bitmapFile.delete();
                    }
                    System.out.println("----------------  文件大小： " + bitmapFile.length());
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                } catch(Exception e) {
                	e.printStackTrace();
                } finally {
                	try {
                		 fos.flush();
                         fos.close();  
                	} catch (Exception e) {
                    	e.printStackTrace();
					}
                }
                
                
                
                
                Message msg = handler.obtainMessage(0, bitmap);  
                handler.sendMessage(msg);  
            }  
        }.start();  
          
        return null;  
    }  

    private String getFileName(final String imageURL) {
    	try {
    		return imageURL.substring(imageURL.lastIndexOf("/") + 1);
    	} catch(Exception e) {
    		return "";
    	}
    	
    }
    public void clearImageCache() {
    	imageCache.clear();
    }
	public interface ImageCallBack {  
        public void imageLoad(final ImageView imageView, final Bitmap bitmap);  
    }  
	private String getLocalPath() {
    	switch(iconType) {
    	case headIcon:
    		iconPath = headPath;
    		break;
    	case wineIcon:
    		iconPath = winePath;
    		break;
    	case mealIcon:
    		iconPath = mealPath;
    		break;
    	case cateIcon:
    		iconPath = catePath;
    		break;
    	case restaurantIcon:
    		iconPath = restaurantPath;
    		break;
		default:
			iconPath = "";
			break;
    	}
		return rootPath + iconPath;
	}
	public void setIconType(int iconType) {
		switch(iconType) {
    	case headIcon:
    	case wineIcon:
    	case mealIcon:
    	case cateIcon:
    	case restaurantIcon:
    		this.iconType = iconType;
    		break;
		default:
			this.iconType = 0;
			break;
    	}
	}
}
